/**
 * Copyright (C) 2020-2021   江西省农村信用社联合社
 * All rights reserved
 */
package com.liuyucheng.idea_springboot.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@Slf4j
@EnableAsync
public class AsyncThreadPoolConfig implements AsyncConfigurer {

    @Bean(name = "asyncExecutor")
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(8);
        //线程池最大线程数
        executor.setMaxPoolSize(8);
        //线程队列最大阻塞线程数
        executor.setQueueCapacity(256);
        //线程池中线程最大空闲存活时间
        executor.setKeepAliveSeconds(60);
        //核心线程是否允许超时，默认：false
        executor.setAllowCoreThreadTimeOut(false);
        //线程名称前缀
        executor.setThreadNamePrefix("Async-Worker-");
        //IOC容器关闭时是否则色等待剩余的任务执行完成，默认：false（ture则必须设置setAwaitTerminationSeconds）
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //阻塞IOC容器关闭的时间
        executor.setAwaitTerminationSeconds(60);

        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.initialize();

        return executor;
    }

    /**
     * 异常捕获
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler() ;
    }

    @SuppressWarnings("all")
    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler{
        @Override
        public void handleUncaughtException(Throwable ex, Method method, Object... params) {
            log.error("AsyncError: {}, method: {}, Param: {}, Error: {}",
                    ex.getMessage(),method.getName(), JSON.toJSON(params),ex);
        }
    }
}
